package com.beyondsoft.mcms.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.beyondsoft.mcms.common.CommonUtils;
import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.domain.Category;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.domain.Users;
import flexjson.JSONSerializer;

@RequestMapping("/memberinfoes")
@Controller
@RooWebScaffold(path = "memberinfoes", formBackingObject = MemberInfo.class)
@RooWebFinder
public class MemberInfoController {

    @RequestMapping(params = { "find=ByMemberNameLikeAndBusinessTypeAndPositionType", "form" }, method = RequestMethod.GET)
    public String findMemberInfoesByMemberNameLikeAndBusinessTypeAndPositionTypeForm(Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("memberName", null);
        request.getSession().setAttribute("positionType", null);
        request.getSession().setAttribute("businessType", null);
        return findMemberInfoesByMemberNameLikeAndBusinessTypeAndPositionType(null, null, null, uiModel);
    }

    @RequestMapping(params = "find=ByMemberNameLikeAndBusinessTypeAndPositionType", method = RequestMethod.GET)
    public String findMemberInfoesByMemberNameLikeAndBusinessTypeAndPositionType(@RequestParam(value = "memberName", required = false) String memberName, @RequestParam(value = "positionType", required = false) Item positionType, @RequestParam(value = "businessType", required = false) Item businessType, Model uiModel) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String page = request.getParameter("page");
        String size = request.getParameter("size");
        int sizeNo = size == null ? 10 : Integer.valueOf(size);
        int pageNo = page == null ? 1 : Integer.valueOf(page);
        if (page != null && size != null) {
            memberName = (String) request.getSession().getAttribute("memberName");
            positionType = (Item) request.getSession().getAttribute("positionType");
            businessType = (Item) request.getSession().getAttribute("businessType");
        } else {
            request.getSession().setAttribute("memberName", memberName);
            request.getSession().setAttribute("positionType", positionType);
            request.getSession().setAttribute("businessType", businessType);
        }
        uiModel.addAttribute("memberName", memberName);
        uiModel.addAttribute("positionType", positionType);
        uiModel.addAttribute("businessType", businessType);
        return list(pageNo, sizeNo, uiModel);
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        List<Item> businesstypes = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.BUSINESS_TYPE)), true).getResultList();
        uiModel.addAttribute("businesstypes", businesstypes);
        List<Item> positiontypes = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.POSITION_TYPE)), true).getResultList();
        uiModel.addAttribute("positiontypes", positiontypes);
        String memberName = (String) uiModel.asMap().get("memberName");
        Item positionType = (Item) uiModel.asMap().get("positionType");
        Item businessType = (Item) uiModel.asMap().get("businessType");
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        float nrOfPages = 0.0f;
        List<MemberInfo> memberinfoes = MemberInfo.findMemberInfoesByMemberNameLikeAndBusinessTypeAndPositionType(memberName, businessType, positionType).getResultList();
        int lastResult = (memberinfoes.size() > (sizeNo + firstResult)) ? (sizeNo + firstResult) : memberinfoes.size();
        nrOfPages = (float) memberinfoes.size() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        uiModel.addAttribute("memberinfoes", memberinfoes.subList(firstResult, lastResult));
        uiModel.addAttribute("find", "ByMemberNameLikeAndBusinessTypeAndPositionType"); // differ
        // non-query
        // request
        uiModel.addAttribute("selectQueryIds", (positionType == null ? "-1" : positionType.getId()) + "," + (businessType == null ? "-1" : businessType.getId()));
        addDateTimeFormatPatterns(uiModel);
        return "memberinfoes/list";
    }

    @RequestMapping(params = { "find=ByConference", "json" }, method = RequestMethod.GET, produces = "application/json")
    public void findMemberInfoesByConference(Long conference, HttpServletResponse response) {
        List<MemberInfo> list = MemberInfo.findMemberInfoesByConference(conference).getResultList();
        try {
            String reponseStr = new JSONSerializer().include("id", "memberName").serialize(list);
            response.getWriter().write(reponseStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        MemberInfo memberInfo = new MemberInfo();
        populateEditForm(uiModel, memberInfo);
        List<String[]> dependencies = new ArrayList<String[]>();
        List<Item> items = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.POSITION_TYPE)), true).getResultList();
        if (items == null || items.size() == 0) {
            dependencies.add(new String[] { "positiontype", "items" });
        } else {
            memberInfo.setPositionType(Item.findItem(Constants.POSITION_ORDINARY));
        }
        items = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.BUSINESS_TYPE)), true).getResultList();
        if (items == null || items.size() == 0) {
            dependencies.add(new String[] { "businesstype", "items" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "memberinfoes/create";
    }

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid MemberInfo memberInfo, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors() || !validMemberInfo(memberInfo, bindingResult)) {
            populateEditForm(uiModel, memberInfo);
            return "memberinfoes/create";
        }
        uiModel.asMap().clear();
        String username = CommonUtils.getCurrentUsername();
        memberInfo.setRigesterDate(new Date());
        memberInfo.setCreatedBy(username);
        memberInfoService.saveMemberInfo(memberInfo);
        return "redirect:/memberinfoes/" + encodeUrlPathSegment(memberInfo.getId().toString(), httpServletRequest);
    }

    private boolean validMemberInfo(MemberInfo memberInfo, BindingResult bindingResult) {
        boolean returnRlt = true;
        if (Users.findUsersesByUsernameEquals(memberInfo.getUsername()).getResultList().size() != 0) {
            bindingResult.rejectValue("username", "users_field_username_exist");
            returnRlt = false;
        }
        if (MemberInfo.findMemberInfoesByMemberNameEquals(memberInfo.getMemberName()).getResultList().size() != 0) {
            bindingResult.rejectValue("memberName", "memberinfo_field_membername_exist");
            returnRlt = false;
        }
        return returnRlt;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        MemberInfo memberInfo = MemberInfo.findMemberInfo(id);
        memberInfoService.deleteMemberInfo(memberInfo);
        uiModel.addAttribute("find", "ByMemberNameLikeAndBusinessTypeAndPositionType"); // differ
        // non-query
        // request
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/memberinfoes";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid MemberInfo memberInfo, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, memberInfo);
            return "memberinfoes/update";
        }
        uiModel.asMap().clear();
        memberInfo.setUpdateDate(new Date());
        memberInfo.setUpdatedBy(CommonUtils.getCurrentUsername());
        memberInfoService.updateMemberInfo(memberInfo);
        return "redirect:/memberinfoes/" + encodeUrlPathSegment(memberInfo.getId().toString(), httpServletRequest);
    }

    void populateEditForm(Model uiModel, MemberInfo memberInfo) {
        uiModel.addAttribute("memberInfo", memberInfo);
        addDateTimeFormatPatterns(uiModel);
        TypedQuery<Item> businesstypes = Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.BUSINESS_TYPE)), true);
        uiModel.addAttribute("businesstypes", businesstypes.getResultList());
        uiModel.addAttribute("positiontypes", Item.findItemsByCategoryAndIsValid(Category.findCategory(new Long(Constants.POSITION_TYPE)), true).getResultList());
    }

    @RequestMapping(value = "/{id}", params = "report", method = RequestMethod.GET)
    public String reportByMemberInfo(@PathVariable("id") Long id, Model uiModel, HttpServletRequest httpServletRequest) {
        return "redirect:/advices/reportByMemberInfo?memberInfo=" + encodeUrlPathSegment(id.toString(), httpServletRequest);
    }
}
